package info.maxhis.util;

import info.maxhis.bn.BaseActivity;

import java.util.Calendar;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;

public class GoogleCalendarUtil {
	
	private Context mContext;
	private SharedData share;
	private static String calanderURL = "";
	private static String calanderEventURL = "";
    private static String calanderRemiderURL = "";
    
    public GoogleCalendarUtil(Context mContext) {
		super();
		this.mContext = mContext;
		share = new SharedData(mContext);
	}

	//为了兼容不同版本的日历,2.2以后url发生改变
	static{
		if(Integer.parseInt(Build.VERSION.SDK) >= 8){
			calanderURL = "content://com.android.calendar/calendars";
			calanderEventURL = "content://com.android.calendar/events";
			calanderRemiderURL = "content://com.android.calendar/reminders";
		}else{
			calanderURL = "content://calendar/calendars";
			calanderEventURL = "content://calendar/events";
			calanderRemiderURL = "content://calendar/reminders";		
		}
	}
	
	/**
	 * 添加生日信息到Google Calendar
	 * @return
	 */
	public void addToGoogleCalendar(String name, Calendar birthday) {
		//获取要出入的gmail账户的id
		String calId = "";
		Cursor userCursor = mContext.getContentResolver().query(Uri.parse(calanderURL), null, 
				null, null, null);
		if(userCursor.getCount() > 0){
			userCursor.moveToFirst();
			calId = userCursor.getString(userCursor.getColumnIndex("_id"));
			
		}
		ContentValues event = new ContentValues();
    	event.put("title", name + "生日提醒");
    	event.put("description", name + "生日到了，记得问候！");

    	event.put("calendar_id",calId);
    	
    	birthday.set(Calendar.HOUR_OF_DAY, 8);
    	long start = birthday.getTime().getTime();
    	birthday.set(Calendar.HOUR_OF_DAY, 12);
    	long end = birthday.getTime().getTime();
    	
    	event.put("dtstart", start);
    	event.put("dtend", end);
    	event.put("allDay", 1); // 0 for false, 1 for true 
    	event.put("hasAlarm",1);
    	
    	Uri newEvent = mContext.getContentResolver().insert(Uri.parse(calanderEventURL), event);
    	long id = Long.parseLong( newEvent.getLastPathSegment() );
    	ContentValues values = new ContentValues();
        values.put( "event_id", id );
        
        //提前提醒
        int advanceDays = share.getAdvanceTime();
        if (advanceDays == 0) {
        	// 默认提前十分钟
        	values.put( "minutes", 10);
		} else {
			values.put( "minutes", advanceDays * 24 * 60);
		}
        mContext.getContentResolver().insert(Uri.parse(calanderRemiderURL), values);
	}
}

